<?php defined('SYSPATH') or die('No direct script access.');

 class Controller_Model_Post extends Controller_Base{

    public function action_index(){

      

      $id=$this->request->param("id")?$this->request->param("id"):$this->request->post("id");

      if(empty($id)){

        if($this->request-> is_ajax()){

          $result=array();

          $result['code']='0x00001';

          exit(json_encode($result));

        }
        else{

          $this->redirect("/");

        }
      }

      $model_post=new Model_Post();

      $post=$model_post->getPostById($id);

      if(empty($post)){

        if($this->request-> is_ajax()){

            $result=array();

            $result['code']='0x00001';

            exit(json_encode($result));
        }
        else{

          $this->redirect("/");

        }
      }
      else{

          if($this->request-> is_ajax()){

            $result=array();

            $result['code']='0x00000';

            $view=View::factory('post/block/detail');

            $view->post=$post;

            $result['data']=$view->render();

            exit(json_encode($result));
          }
          else{

              $this->template->title = __($post['title']);

              $view=View::factory('post/index');

              $view->post=$post;

              $this->template->content =$view;

          }
      }

    }
      //
    public function action_load(){

      $user=Session::instance()->get('user');

      $result=array();

      if(!empty($user)){

        $userid=$user['userid'];

        $cache = Cache::instance();

        $id=$this->request->post("id");

        $model_album=new Model_Album();

        $data=array();

        $tags = $cache->get('site_tags',NULL);

        if(empty($tags)){

           $tags=DB::select(array('tagid','id'),'caption')
           ->from('tag')->order_by('createdon', 'desc')->limit(20)->execute()->as_array();
        }

        $data['tags']=$tags;

        $result['code']='0x00000';

        if(!empty($id)){

          $model_post=new Model_Post();

          $data['post']=$model_post->getUserPost($userid,$id);

        }

        $result['data']=Block_Post::load($data);

      }
      else{

        $result['code']='0x00001';

      }

      exit(json_encode($result));
    }
    public function action_saveinfo(){

      $user=Session::instance()->get('user');

      if(!empty($user)){

        $userid=$user['userid'];

        $id=$this->request->post("id");

        $img_info=trim($this->request->post("img_info"));

        $title=trim($this->request->post("title"));

        $description=trim($this->request->post("description"));

        $tags=trim($this->request->post("tags"));

        if(empty($id)){

          exit($this->add($userid,$img_info,$title,$description,$tags));
            
        }
        else{

          exit($this->alter($id,$userid,$img_info,$title,$description,$tags));
          
        }
        
      }
      else{

        $result=array();

        $result['code']='0x00001';

        exit(json_encode($result));

      }

    }

    private function add($userid,$img_info,$title,$description,$tags){

        try{

          $img_info_arr =explode(";", trim($img_info));

          $main_image="";

          $images="";

          $count=count($img_info_arr);

          foreach ($img_info_arr as $i => $image) {

            if($i==$count-1){

              $images=$images.$image;

            }
            else{

              $images=$images.$image.";";

            }
            
          }

          Database::instance()->begin();

          list($insert_id, $total_rows)= DB::insert('post')

          ->columns(array('userid','title','description','tags','created','images'))
              
          ->values(array($userid,$title,$description,$tags,date("Y-m-d h:i:sa"),$images))->execute();

           foreach ($img_info_arr as $i => $image) {

              $oldFile='temp/t/'.$image;

              if(file_exists($oldFile)){

                $newFile='temp/post/post'.$insert_id."-M-".$image;

                copy($oldFile,$newFile);

                $img = Image::factory($newFile);

                $filename ='temp/post/post'.$insert_id."-M500-".$image;

                $img->resize(500, NULL)->save($filename);

                $filename ='temp/post/post'.$insert_id."-M260-".$image;

                $img->resize(260, NULL)->save($filename);

                $filename ='temp/post/post'.$insert_id."-M100-".$image;

                $img->resize(100, NULL)->save($filename);

                unlink($oldFile);

              }
              
          }

          Database::instance()->commit();

          $user=Session::instance()->get('user');

          $post_list=array();

          $post_list[]=array(
            'id'=>$insert_id,
            'title'=>$title,
            'description'=>$description,
            'images'=>$images
          );

          $post_info=Block_User::post_list($user,$post_list);

          return json_encode(array("code"=>"0x00000",'id'=>$insert_id,'title'=>$title,'post_info'=>$post_info));

        }
        catch (Exception $e) {

          Database::instance()->rollback();

          return json_encode(array("info"=>"上传失败","code"=>"0x0000x"));
        }

    }

    private function alter($id,$userid,$img_info,$title,$description,$tags){

      try{

         $img_info_arr =explode(";", trim($img_info));

          $count=count($img_info_arr);

          $images="";

          foreach ($img_info_arr as $i => $image) {

            if($i==$count-1){

              $images=$images.$image;

            }
            else{

              $images=$images.$image.";";

            }
            
          }

          Database::instance()->begin();

          $total_rows=DB::update('post')
            ->set(array('title'=>$title,
                'description'=>$description,
                'images'=>$images,
                'tags'=>$tags))
            ->where('postid','=',$id)
            ->and_where('userid','=',$userid)
            ->execute();

          foreach ($img_info_arr as $i => $image) {

              $oldFile='temp/t/'.$image;

              $ci='temp/post/post'.$id."-M-".$image;

              if(!file_exists($ci)){

                if(file_exists($oldFile)){

                  copy($oldFile,$ci);

                  $img = Image::factory($ci);

                  $filename ='temp/post/post'.$id."-M500-".$image;

                  $img->resize(500, NULL)->save($filename);

                  $filename ='temp/post/post'.$id."-M260-".$image;

                  $img->resize(260, NULL)->save($filename);

                  $filename ='temp/post/post'.$id."-M100-".$image;

                  $img->resize(100, NULL)->save($filename);

                  unlink($oldFile);

                }

              }
              else{

                  $filename ='temp/post/post'.$id."-M500-".$image;

                  $img = Image::factory($ci);

                  if(!file_exists($filename)){

                    $img->resize(500, NULL)->save($filename);

                  }

                  $filename ='temp/post/post'.$id."-M260-".$image;

                  if(!file_exists($filename)){

                    $img->resize(260, NULL)->save($filename);
                    
                  }
                
                  $filename ='temp/post/post'.$id."-M100-".$image;

                  if(!file_exists($filename)){

                    $img->resize(100, NULL)->save($filename);
                    
                  }
                  
              }
          }

          Database::instance()->commit();

          $post_list=array(
            'id'=>$id,
            'title'=>$title,
            'description'=>$description,
            'image'=>Lib_Image::getPostImage($id,$images,260)
          );

          return json_encode(array("code"=>"0x00000",'id'=>$id,'title'=>$title,'post_list'=>$post_list));

      }
      catch (Exception $e) {

        Database::instance()->rollback();

        return json_encode(array("info"=>"上传失败","code"=>"0x0000x"));
      } 
        
    }

    public function action_interact(){

      $t=$this->request->post("t");

      $post_id=$this->request->post("id");

      $result=array();

      if(empty($post_id)){

        $result['code']='0x0000x';

        exit(json_encode($result));

      }

      $user=Session::instance()->get('user');

      if(empty($user)){

        $userid="0";

      }

      else{

        $userid=$user['userid'];

      }

      if($t=="praiseup"){

        exit($this->praiseup($userid,$post_id));
               
      }

      else{

        exit($this->praisedown($userid,$post_id));

      }

    }

    private function praiseup($userid,$post_id){

      $result=array();

      $sql="select t.interactid id,t.praiseup
           from interact t
           where t.postid='$post_id'
           and t.userid='$userid' limit 1";

      $query=DB::query(Database::SELECT,$sql)->execute();

      $c=$query->as_array();

      if(empty($c)){

        list($insert_id, $total_rows)= DB::insert('interact')

          ->columns(array('userid','postid','praiseup','praisedown','createdon'))
              
          ->values(array($userid,$post_id,'1','0',date("Y-m-d h:i:sa")))->execute();

          if(empty($userid)){

            Session::instance()->set('interact'.$post_id.'praiseup','1');

          }

          $result['code']='0x00000';
      
      }   
      else{

        if(empty($userid)){

          $s_interact=Session::instance()->get('interact'.$post_id.'praiseup');

          if(empty($s_interact)){

            $sql="update interact
            set praiseup=praiseup+1
            where postid='$post_id'
            and userid='0'";

            DB::query(null,$sql)->execute();

            Session::instance()->set('interact'.$post_id.'praiseup','1');

            $result['code']='0x00000';

          }

          else{

            $sql="update interact
            set praiseup=praiseup-1
            where postid='$post_id'
            and praiseup>0
            and userid='0'";

            DB::query(null,$sql)->execute();

            Session::instance()->set('interact'.$post_id.'praiseup','');

            $result['code']='0x00003';

          }

        }

        else{

            DB::update('interact')

            ->set(array("praiseup"=>"0"))

            ->where('postid','=',$post_id)

            ->and_where("userid","=",$userid)
            
            ->execute();

            Session::instance()->set('interact'.$post_id.'praiseup','');

            $result['code']='0x00003';

        }

      }

      return json_encode($result);

    }

    private function praisedown($userid,$post_id){

      $result=array();

      $sql="select t.interactid id,t.praisedown
           from interact t
           where t.postid='$post_id'
           and t.userid='$userid' limit 1";

      $query=DB::query(Database::SELECT,$sql)->execute();

      $c=$query->as_array();

      if(empty($c)){

        list($insert_id, $total_rows)= DB::insert('interact')

          ->columns(array('userid','postid','praiseup','praisedown','createdon'))
              
          ->values(array($userid,$post_id,'0','1',date("Y-m-d h:i:sa")))->execute();

          if(empty($userid)){

            Session::instance()->set('interact'.$post_id.'praisedown','1');

          }

          $result['code']='0x00000';
      
      }   
      else{

        if(empty($userid)){

          $s_interact=Session::instance()->get('interact'.$post_id.'praisedown');


          if(empty($s_interact)){

            $sql="update interact
            set praisedown=praisedown+1
            where postid='$post_id'
            and userid='0'";

            DB::query(null,$sql)->execute();

            Session::instance()->set('interact'.$post_id.'praisedown','1');

            $result['code']='0x00000';

          }

          else{

            $sql="update interact
            set praisedown=praisedown-1
            where postid='$post_id'
            and praisedown>0
            and userid='0'";

            DB::query(null,$sql)->execute();

            Session::instance()->set('interact'.$post_id.'praisedown','');

            $result['code']='0x00003';

          }

        }

        else{

            DB::update('interact')

            ->set(array("praisedown"=>"0"))

            ->where('postid','=',$post_id)

            ->and_where("userid","=",$userid)
            
            ->execute();

            $result['code']='0x00003';

        }

      }

      return json_encode($result);

    }

    public function action_remove(){

      $id=$this->request->post("id");

      $user=Session::instance()->get('user');

      $result=array();

      if(!empty($user)){

        $userid=$user["userid"];

        $model=new Model_Post();

        $result=$model->remove($userid,$id);

      }
      else{

        $result['code']='0x00001';

      }

      exit(json_encode($result));
    }
 } 
